package com.yunxi.service.dubboService.impl.sat;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.DictConstant;
import com.yunxi.core.web.LoginInfo;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.hubToBiz.pojo.CustomerClueVO;
import com.yunxi.hubToBiz.pojo.CustomerTestDriveVO;
import com.yunxi.hubToBiz.service.NewCustomerClueService;
import com.yunxi.model.sat.MsgTemplate;
import com.yunxi.model.sat.SatCustomerClue;
import com.yunxi.model.sat.SatMess;
import com.yunxi.model.sat.SatTestDrive;
import com.yunxi.sat.pojo.SatCustomerClueVO;
import com.yunxi.sat.pojo.SatMessAddVO;
import com.yunxi.sat.service.SatCustomerClueDubboService;
import com.yunxi.service.localService.CodeCreateService;
import com.yunxi.service.localService.sat.MsgTemplateService;
import com.yunxi.service.localService.sat.SatCustomerClueService;
import com.yunxi.service.localService.sat.SatMessService;
import com.yunxi.service.localService.sat.SatTestDriveService;
import com.yunxi.sys.pojo.StaffVO;
import com.yunxi.sys.service.StaffDubboService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客户线索,试驾信息下发 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-08-21
 */

public class NewCustomerClueServiceImpl implements NewCustomerClueService {

    @Autowired
    @Qualifier( value = "satCustomerClueDubboServiceImpl")
    SatCustomerClueDubboService satCustomerClueDubboService;

    @Autowired
    @Qualifier(value = "satTestDriveServiceImpl")
    SatTestDriveService satTestDriveService;

    @Autowired
    @Qualifier(value = "satCustomerClueServiceImpl")
    SatCustomerClueService satCustomerClueService;

    @Autowired
    @Qualifier(value = "satMessServiceImpl")
    SatMessService satMessService;

    @Autowired
    @Qualifier(value = "msgTemplateServiceImpl")
    MsgTemplateService msgTemplateService;

    @Autowired
    @Qualifier(value = "staffDubboServiceBiz")
    StaffDubboService staffDubboService;

    @Autowired
    SatMessService satMessServiceImpl;

    @Autowired
    @Qualifier(value = "codeCreateServiceImpl")
    CodeCreateService codeCreateService;


    /**
     * URM ->PMS
     * 推送潜客线索
     * @param list
     * @throws Exception
     */
    @Override
    public ApiResult newCustomerClue(List<CustomerClueVO> list) throws Exception {
        if(list == null || list.size() <= 0) return ResponseUtil.fail(500,"操作失败,线索为空!");
        List<String> msgList = new ArrayList<>();
        List<String> warnList = new ArrayList<>();
        for(CustomerClueVO urmCustomerClueVO : list){
            String customerNo = urmCustomerClueVO.getCustomerNo();
            String clubNo = urmCustomerClueVO.getClubNo();
            String province = urmCustomerClueVO.getProvince();
            String city = urmCustomerClueVO.getCity();
            if (!"1".equals(urmCustomerClueVO.getClubType())) return ResponseUtil.fail(-1,"线索类型错误:"+urmCustomerClueVO.getClubType());
            if(StringUtils.isEmpty(customerNo)){
                return ResponseUtil.fail(Constant.URM_R_CODE_ERR,"操作失败,客户ID为空!");
            }
            if(StringUtils.isEmpty(clubNo)){
                return ResponseUtil.fail(Constant.URM_R_CODE_ERR,"操作失败,线索编号空!");
            }
            if (StringUtils.isNotEmpty(urmCustomerClueVO.getTel()) && urmCustomerClueVO.getTel().length()!=11){
                return ResponseUtil.fail(-1,"操作失败,手机号错误:"+urmCustomerClueVO.getTel());
            }
            if(StringUtils.isEmpty(province) || StringUtils.isEmpty(city)){
                msgList.add(customerNo);
                continue;
            }
            QueryWrapper<SatCustomerClue> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("CLUE_NO",clubNo);
            SatCustomerClue satCustomerClue = satCustomerClueService.getOne(queryWrapper);
            if(satCustomerClue != null && satCustomerClue.getIsGet() != null && satCustomerClue.getIsGet().equals(1)){
                warnList.add(customerNo);
                continue;
            }
            SatCustomerClueVO satCustomerClueVO = new SatCustomerClueVO();
            BeanUtils.copyProperties(urmCustomerClueVO,satCustomerClueVO);
            satCustomerClueVO.setUserSource1(urmCustomerClueVO.getUserSource_1());
            satCustomerClueVO.setUserSource2(urmCustomerClueVO.getUserSource_2());
            satCustomerClueVO.setUserSource3(urmCustomerClueVO.getUserSource_3());
            satCustomerClueVO.setClueSource("urm");
            satCustomerClueVO.setClueType(urmCustomerClueVO.getClubType());
            satCustomerClueVO.setClueNo(clubNo);
            transforLevel(satCustomerClueVO);
            String partnerCode = satCustomerClueVO.getPartnerCode();
            if(StringUtils.isNotEmpty(partnerCode)){
                satCustomerClueVO.setAssignDate(new Date());
                satCustomerClueVO.setIsRemind(0);
                satCustomerClueVO.setIsRemindManager(0);
                pushMsg(satCustomerClueVO, partnerCode);

                CustomerTestDriveVO customerTestDriveVO = new CustomerTestDriveVO();
                customerTestDriveVO.setUserId(customerNo);
                customerTestDriveVO.setKunnrcode(partnerCode);
                List<String> salesList = satTestDriveService.getCustomerSales(customerTestDriveVO);
                if(salesList != null && salesList.size() > 0){
                    sendMsg(customerNo, urmCustomerClueVO.getCustomerName(), "1", 2, salesList.get(0));
                    //如果线索带渠道code,根据客户编号,渠道code查询唯一一条客户信息,取销售顾问编号
                    //如果能取到销售顾问,则变更线索为已领取状态
                    satCustomerClueVO.setGetUser(salesList.get(0));
                    satCustomerClueVO.setIsGet(1);
                    satCustomerClueVO.setIsSelf(0);
                    satCustomerClueVO.setGetDate(new Date());
                }
            }
            if(satCustomerClue != null){
                satCustomerClueVO.setClueId(satCustomerClue.getClueId());
            }
            satCustomerClueDubboService.saveOrUpdate(satCustomerClueVO);
        }
        StringBuilder msg = new StringBuilder("success:线索全部新增成功");
        if(msgList.size() > 0){
            String join = StringUtils.join(msgList, ",");
            msg = new StringBuilder("success:客户编号为:"+join+"的线索因缺失区域信息新增失败;");
        }
        if(warnList.size() > 0){
            String join = StringUtils.join(warnList, ",");
            msg.append("客户编号为:"+join+"的线索因已被领取新增失败;");
        }
        return ResponseUtil.ok(msg);
    }


    /**
     * 转换客户级别为字典
     * @param satCustomerClueVO
     */
    private void transforLevel(SatCustomerClueVO satCustomerClueVO) {
        String level = satCustomerClueVO.getLevel();
        if(StringUtils.isNotEmpty(level)){
            switch (level){
                case "O":
                    satCustomerClueVO.setLevel("1");
                    break;
                case "H":
                    satCustomerClueVO.setLevel("2");
                    break;
                case "A":
                    satCustomerClueVO.setLevel("3");
                    break;
                case "B":
                    satCustomerClueVO.setLevel("4");
                    break;
                case "C":
                    satCustomerClueVO.setLevel("5");
                    break;
                case "其他":
                    satCustomerClueVO.setLevel("6");
                    break;
                case "战败":
                    satCustomerClueVO.setLevel("7");
                    break;
                default:
                    satCustomerClueVO.setLevel("6");
            }
        }
    }

    /**
     * 新增试驾
     * @param customerTestDriveVO
     * @throws Exception
     */
    @Override
    public ApiResult newCustomerTestDrive(CustomerTestDriveVO customerTestDriveVO) throws Exception {
        String userId = customerTestDriveVO.getUserId();
        String name = customerTestDriveVO.getName();
        if(StringUtils.isEmpty(userId) || StringUtils.isEmpty(name)){
            return ResponseUtil.fail(Constant.URM_R_CODE_ERR,"操作失败,客户ID或姓名为空!");
        }
        if (customerTestDriveVO.getPhone().length()!=11)  return ResponseUtil.fail(-1,"手机号错误");
        //试驾
        SatTestDrive satTestDrive = new SatTestDrive();
        satTestDrive.setCustomerNo(userId);
        satTestDrive.setCustomerName(name);
        satTestDrive.setApplyType(1);
        if(StringUtils.isNotEmpty(customerTestDriveVO.getTrailType())){
            satTestDrive.setDriveStyle(Integer.parseInt(customerTestDriveVO.getTrailType()));//试驾方式
        }
        if(StringUtils.isNotEmpty(customerTestDriveVO.getTrailTime())){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = simpleDateFormat.parse(customerTestDriveVO.getTrailTime());
            satTestDrive.setPlanDriveTime(parse);
        }
        satTestDrive.setCertPicFront(customerTestDriveVO.getCertUrl());
        satTestDrive.setCertPicBack(customerTestDriveVO.getDlUrl());
        //等试驾线索被销售领取或经理分配给销售时,取线索的渠道代码填充到试驾信息上
//        satTestDrive.setPartnerCode(customerTestDriveVO.getKunnrcode());//渠道代码
        satTestDrive.setProvinceCode(customerTestDriveVO.getProvinceCode());
        satTestDrive.setCityCode(customerTestDriveVO.getCityCode());
        satTestDrive.setCountryCode(customerTestDriveVO.getCountryCode());
        satTestDrive.setAddress(customerTestDriveVO.getAddress());
        satTestDrive.setCityName(customerTestDriveVO.getCityName());
        satTestDrive.setCertNo(customerTestDriveVO.getCertNo());

        //线索
        SatCustomerClue satCustomerClue = new SatCustomerClue();
        satCustomerClue.setClueId(codeCreateService.createCode("LS", "yyyyMMdd", 4));
        satCustomerClue.setClueNo(satCustomerClue.getClueId());
        satCustomerClue.setPartnerCode(customerTestDriveVO.getKunnrcode());//渠道代码
        if(StringUtils.isNotEmpty(customerTestDriveVO.getKunnrcode())){
            satCustomerClue.setAssignDate(new Date());
        }
        satCustomerClue.setClueType("2");
        satCustomerClue.setCustomerNo(userId);
        satCustomerClue.setCustomerName(name);
        satCustomerClue.setTel(customerTestDriveVO.getPhone());
        satCustomerClue.setProvince(customerTestDriveVO.getProvinceCode());
        satCustomerClue.setCity(customerTestDriveVO.getCityCode());

        satCustomerClue.setClueSource("app");

        //3.查询系统内是否存在该客户信息,存在则对所属销售顾问推送消息,告知客户已申请试驾
        if (StringUtils.isNotEmpty(customerTestDriveVO.getKunnrcode())){
            List<String> list = satTestDriveService.getCustomerSales(customerTestDriveVO);
            if(list != null && list.size() > 0){
                for (String userCode : list){
                    sendMsg(userId, name, "2", 10, userCode);
                }

                //如果线索带渠道code,根据客户编号,渠道code查询唯一一条客户信息,取销售顾问编号
                //如果能取到销售顾问,则变更线索为已领取状态,试驾信息写入渠道代码,所属顾问
//                if(StringUtils.isNotEmpty(customerTestDriveVO.getKunnrcode())){
                    satTestDrive.setSalesConsultantNo(list.get(0));
                    satTestDrive.setPartnerCode(customerTestDriveVO.getKunnrcode());
                    satCustomerClue.setGetUser(list.get(0));
                    satCustomerClue.setIsGet(1);
                    satCustomerClue.setIsSelf(0);
                    satCustomerClue.setGetDate(new Date());
                    sendMsg(userId, name, "1", 2, list.get(0));
//                }
            }
        }
        //1.新增试驾
        satTestDriveService.saveOrUpdate(satTestDrive);
        //2.新增试驾线索
        satCustomerClue.setBusinessKey(satTestDrive.getDriveId());
        satCustomerClueService.saveOrUpdate(satCustomerClue);
        return ResponseUtil.ok("success");
    }

    private void sendMsg(String userId, String name, String s, int i, String s2) throws InvocationTargetException, IllegalAccessException {
        SatMessAddVO satMessAddVO = new SatMessAddVO();
        satMessAddVO.setType(s);
        satMessAddVO.setTemplateType(i);
        satMessAddVO.setCustomerName(name);
        satMessAddVO.setCustomerNo(userId);
        satMessAddVO.setSalesConsultantNo(s2);
        satMessAddVO.setReceiveRoleCode("rolePartnerSale");
        satMessService.newMess(satMessAddVO);
    }

    private void pushMsg(SatCustomerClueVO satCustomerClueVO, String partnerCode) throws InvocationTargetException, IllegalAccessException {
        QueryWrapper<MsgTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("TYPE", 2);
        MsgTemplate msgTemplate = msgTemplateService.getOne(queryWrapper);
        //查询该渠道商下所有所有销售经理
        LoginInfo loginInfo1 = new LoginInfo();
        loginInfo1.setPartnerCode(partnerCode);
        ApiResult apiResult = staffDubboService.listStaffByRoleCode(DictConstant.USER_ROLE_MANAGER, loginInfo1);
        Object data = apiResult.getData();
        List<StaffVO> staffVOList = new ArrayList<>();
        if (data != null) {
            staffVOList = (List<StaffVO>) apiResult.getData();
        }
        List<SatMess> satMessList = new ArrayList<>();
        for (StaffVO vo : staffVOList) {
            SatMess satMess = new SatMess();
            satMess.setType("1");//线索分配
            satMess.setCustomerNo(satCustomerClueVO.getCustomerNo());
            satMess.setCustomerName(satCustomerClueVO.getCustomerName());
            satMess.setSalesConsultantNo(vo.getAccountNo());
            satMess.setOperaRoleCode(DictConstant.USER_ROLE_AREAMANAGER);
            satMess.setReceiveRoleCode(DictConstant.USER_ROLE_MANAGER);
            satMess.setBusinessKey(satCustomerClueVO.getBusinessKey());
            satMess.setInfo(msgTemplate.getInfo());
            satMessList.add(satMess);
        }

        satMessServiceImpl.newMess2(satMessList);
    }
}
